import 'package:flutter/material.dart';
import 'package:flutter_base/page/common/navigation_bar_item.dart';

///
/// @DIR_PATH：lib/page/common
/// @TIME：2024/6/11 11:52
/// @AUTHOR：starr
/// 通用的底部导航栏组件

class NavigationBarWidget extends StatefulWidget {
  NavigationBarWidget(
      {super.key,
      required this.pages,
      required this.labels,
      required this.icons,
      required this.onPageChange,
      required this.controller,
      this.activeIcons,
      this.currentIndex}) {
    if (pages.length != labels.length &&
        pages.length != icons.length &&
        pages.length != activeIcons?.length) {
      throw Exception("数组长度不一致");
    }
  }

  //页面数组
  final List<Widget> pages;

  //底部标题
  final List<String> labels;

  //导航栏icon数组：未选中
  final List<Widget> icons;

  //导航栏icon数组：选中
  final List<Widget>? activeIcons;

  //page的控制器
  final PageController controller;

  //当前页面
  int? currentIndex;

  //切换事件
  ValueChanged<int>? onPageChange;

  @override
  State createState() {
    return _NavigationBarWidgetState();
  }
}

class _NavigationBarWidgetState extends State<NavigationBarWidget> {
  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    return Scaffold(
      //页面的主内容区
      //可以是单独的StatefulWidget 也可以是当前页面构建的如Text文本组件
      body: SafeArea(
        child: PageView(
          //设置PageView不可滑动切换
          // physics: const NeverScrollableScrollPhysics(),
          //PageView的控制器
          controller: widget.controller,
          //PageView中的四个子页面
          children: widget.pages,
          onPageChanged: (index) {
            setState(() {
              widget.currentIndex = index;
            });
          },
        ),
      ),
      //底部导航栏
      //通过设置主题去除波纹效果
      bottomNavigationBar: Theme(
          data: Theme.of(context).copyWith(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent),
          child: buildBottomNavigation()),
    );
  }

  BottomNavigationBar buildBottomNavigation() {
    return BottomNavigationBar(
      items: _barItemList(),
      type: BottomNavigationBarType.fixed,
      currentIndex: widget.currentIndex ?? 0,
      onTap: (index) {
        widget.controller.animateToPage(index,
            duration: const Duration(microseconds: 400),
            curve: Curves.easeInOutQuart);
        widget.onPageChange?.call(index);
        setState(() {
          widget.currentIndex = index;
        });
      },
    );
  }

  List<BottomNavigationBarItem> _barItemList() {
    final List<BottomNavigationBarItem> items = [];
    for (int index = 0; index < widget.pages.length; index++) {
      items.add(BottomNavigationBarItem(
          icon: widget.icons[index],
          label: widget.labels[index],
          activeIcon: NavigationBarItem(builder: (context) {
            return widget.activeIcons?[index] ?? widget.icons[index];
          })));
    }
    return items;
  }
}
